
#include <stdlib.h>
#include <sys/cdefs.h>
#include "sdkconfig.h"
#if CONFIG_LCD_ENABLE_DEBUG_LOG
// The local log level must be defined before including esp_log.h
// Set the maximum log level for this source file
#define LOG_LOCAL_LEVEL ESP_LOG_DEBUG
#endif
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_lcd_panel_interface.h"
#include "esp_lcd_panel_io.h"
#include "esp_lcd_panel_vendor.h"
#include "esp_lcd_panel_ops.h"
#include "esp_lcd_panel_commands.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "esp_check.h"
#include "r61581_conf.h"

static const char* TAG = "lcd_panel.r61581";

static esp_err_t panel_r61581_del(esp_lcd_panel_t* panel);
static esp_err_t panel_r61581_reset(esp_lcd_panel_t* panel);
static esp_err_t panel_r61581_init(esp_lcd_panel_t* panel);
static esp_err_t panel_r61581_draw_bitmap(esp_lcd_panel_t* panel, int x_start, int y_start, int x_end, int y_end, const void* color_data);
static esp_err_t panel_r61581_invert_color(esp_lcd_panel_t* panel, bool invert_color_data);
static esp_err_t panel_r61581_mirror(esp_lcd_panel_t* panel, bool mirror_x, bool mirror_y);
static esp_err_t panel_r61581_swap_xy(esp_lcd_panel_t* panel, bool swap_axes);
static esp_err_t panel_r61581_set_gap(esp_lcd_panel_t* panel, int x_gap, int y_gap);
static esp_err_t panel_r61581_disp_on_off(esp_lcd_panel_t* panel, bool off);

typedef struct
{
    esp_lcd_panel_t           base;
    esp_lcd_panel_io_handle_t io;
    int                       reset_gpio_num;
    bool                      reset_level;
    int                       x_gap;
    int                       y_gap;
    uint8_t                   fb_bits_per_pixel;
    uint8_t                   madctl_val;    // save current value of LCD_CMD_MADCTL register
    uint8_t                   colmod_cal;    // save surrent value of LCD_CMD_COLMOD register
} r61581_panel_t;

esp_err_t esp_lcd_new_panel_r61581(const esp_lcd_panel_io_handle_t io, const esp_lcd_panel_dev_config_t* panel_dev_config, esp_lcd_panel_handle_t* ret_panel)
{
#if CONFIG_LCD_ENABLE_DEBUG_LOG
    esp_log_level_set(TAG, ESP_LOG_DEBUG);
#endif
    esp_err_t       ret    = ESP_OK;
    r61581_panel_t* r61581 = NULL;
    ESP_GOTO_ON_FALSE(io && panel_dev_config && ret_panel, ESP_ERR_INVALID_ARG, err, TAG, "invalid argument");
    r61581 = calloc(1, sizeof(r61581_panel_t));
    ESP_GOTO_ON_FALSE(r61581, ESP_ERR_NO_MEM, err, TAG, "no mem for r61581 panel");

    if(panel_dev_config->reset_gpio_num >= 0)
    {
        gpio_config_t io_conf = {
            .mode         = GPIO_MODE_OUTPUT,
            .pin_bit_mask = 1ULL << panel_dev_config->reset_gpio_num,
        };
        ESP_GOTO_ON_ERROR(gpio_config(&io_conf), err, TAG, "configure GPIO for RST line failed");
    }

    switch(panel_dev_config->rgb_endian)
    {
        case LCD_RGB_ENDIAN_RGB:
            r61581->madctl_val = 0;
            break;
        case LCD_RGB_ENDIAN_BGR:
            r61581->madctl_val |= LCD_CMD_BGR_BIT;
            break;
        default:
            ESP_GOTO_ON_FALSE(false, ESP_ERR_NOT_SUPPORTED, err, TAG, "unsupported color space");
            break;
    }

    uint8_t fb_bits_per_pixel = 0;
    switch(panel_dev_config->bits_per_pixel)
    {
        case 16:    // RGB565
            r61581->colmod_cal = 0x55;
            fb_bits_per_pixel  = 16;
            break;
        case 18:    // RGB666
            r61581->colmod_cal = 0x66;
            // each color component (R/G/B) should occupy the 6 high bits of a byte, which means 3 full bytes are required for a pixel
            fb_bits_per_pixel = 24;
            break;
        default:
            ESP_GOTO_ON_FALSE(false, ESP_ERR_NOT_SUPPORTED, err, TAG, "unsupported pixel width");
            break;
    }

    r61581->io                = io;
    r61581->fb_bits_per_pixel = fb_bits_per_pixel;
    r61581->reset_gpio_num    = panel_dev_config->reset_gpio_num;
    r61581->reset_level       = panel_dev_config->flags.reset_active_high;
    r61581->base.del          = panel_r61581_del;
    r61581->base.reset        = panel_r61581_reset;
    r61581->base.init         = panel_r61581_init;
    r61581->base.draw_bitmap  = panel_r61581_draw_bitmap;
    r61581->base.invert_color = panel_r61581_invert_color;
    r61581->base.set_gap      = panel_r61581_set_gap;
    r61581->base.mirror       = panel_r61581_mirror;
    r61581->base.swap_xy      = panel_r61581_swap_xy;
    r61581->base.disp_on_off  = panel_r61581_disp_on_off;
    *ret_panel                = &(r61581->base);
    ESP_LOGD(TAG, "new r61581 panel @%p", r61581);

    return ESP_OK;

err:
    if(r61581)
    {
        if(panel_dev_config->reset_gpio_num >= 0)
        {
            gpio_reset_pin(panel_dev_config->reset_gpio_num);
        }
        free(r61581);
    }
    return ret;
}

static esp_err_t panel_r61581_del(esp_lcd_panel_t* panel)
{
    r61581_panel_t* r61581 = __containerof(panel, r61581_panel_t, base);

    if(r61581->reset_gpio_num >= 0)
    {
        gpio_reset_pin(r61581->reset_gpio_num);
    }
    ESP_LOGD(TAG, "del r61581 panel @%p", r61581);
    free(r61581);
    return ESP_OK;
}

static esp_err_t panel_r61581_reset(esp_lcd_panel_t* panel)
{
    r61581_panel_t*           r61581 = __containerof(panel, r61581_panel_t, base);
    esp_lcd_panel_io_handle_t io     = r61581->io;

    ESP_LOGD(TAG, "panel_r61581_reset @%p", r61581);

    // perform hardware reset
    if(r61581->reset_gpio_num >= 0)
    {
        gpio_set_level(r61581->reset_gpio_num, r61581->reset_level);
        vTaskDelay(pdMS_TO_TICKS(10));
        gpio_set_level(r61581->reset_gpio_num, !r61581->reset_level);
        vTaskDelay(pdMS_TO_TICKS(10));
    }
    else
    {    // perform software reset
        esp_lcd_panel_io_tx_param(io, LCD_CMD_SWRESET, NULL, 0);
        vTaskDelay(pdMS_TO_TICKS(20));    // spec, wait at least 5m before sending new command
    }

    return ESP_OK;
}

static esp_err_t panel_r61581_init(esp_lcd_panel_t* panel)
{
    r61581_panel_t*           r61581 = __containerof(panel, r61581_panel_t, base);
    esp_lcd_panel_io_handle_t io     = r61581->io;

    ESP_LOGD(TAG, "panel_r61581_init @%p", r61581);

    esp_lcd_panel_io_tx_param(io, cmd_B0[0], &cmd_B0[1], sizeof(cmd_B0) - 1);
    esp_lcd_panel_io_tx_param(io, cmd_B3[0], &cmd_B3[1], sizeof(cmd_B3) - 1);
    esp_lcd_panel_io_tx_param(io, cmd_C0[0], &cmd_C0[1], sizeof(cmd_C0) - 1);
    esp_lcd_panel_io_tx_param(io, cmd_C1[0], &cmd_C1[1], sizeof(cmd_C1) - 1);
    esp_lcd_panel_io_tx_param(io, cmd_C4[0], &cmd_C4[1], sizeof(cmd_C4) - 1);
    esp_lcd_panel_io_tx_param(io, cmd_C6[0], &cmd_C6[1], sizeof(cmd_C6) - 1);
    esp_lcd_panel_io_tx_param(io, cmd_C8[0], &cmd_C8[1], sizeof(cmd_C8) - 1);    // Gamma
    esp_lcd_panel_io_tx_param(io, cmd_36[0], &cmd_36[1], sizeof(cmd_36) - 1);
    esp_lcd_panel_io_tx_param(io, cmd_3A[0], &cmd_3A[1], sizeof(cmd_3A) - 1);
    esp_lcd_panel_io_tx_param(io, cmd_38[0], NULL, 0);
    esp_lcd_panel_io_tx_param(io, cmd_D0[0], &cmd_D0[1], sizeof(cmd_D0) - 1);
    esp_lcd_panel_io_tx_param(io, cmd_D1[0], &cmd_D1[1], sizeof(cmd_D1) - 1);
    esp_lcd_panel_io_tx_param(io, cmd_D2[0], &cmd_D2[1], sizeof(cmd_D2) - 1);

    // LCD goes into sleep mode and display will be turned off after power on reset, exit sleep mode first
    esp_lcd_panel_io_tx_param(io, LCD_CMD_SLPOUT, NULL, 0);
    vTaskDelay(pdMS_TO_TICKS(120));
    // esp_lcd_panel_io_tx_param(io, LCD_CMD_MADCTL, (uint8_t[]){
    //                                                   r61581->madctl_val,
    //                                               },
    //                           1);
    // esp_lcd_panel_io_tx_param(io, LCD_CMD_COLMOD, (uint8_t[]){
    //                                                   r61581->colmod_cal,
    //                                               },
    //                           1);

    return ESP_OK;
}

static esp_err_t panel_r61581_draw_bitmap(esp_lcd_panel_t* panel, int x_start, int y_start, int x_end, int y_end, const void* color_data)
{
    r61581_panel_t* r61581 = __containerof(panel, r61581_panel_t, base);
    assert((x_start < x_end) && (y_start < y_end) && "start position must be smaller than end position");
    esp_lcd_panel_io_handle_t io = r61581->io;

    x_start += r61581->x_gap;
    x_end += r61581->x_gap;
    y_start += r61581->y_gap;
    y_end += r61581->y_gap;

    // define an area of frame memory where MCU can access
    esp_lcd_panel_io_tx_param(io, LCD_CMD_CASET, (uint8_t[]){
                                                     (x_start >> 8) & 0xFF,
                                                     x_start & 0xFF,
                                                     ((x_end - 1) >> 8) & 0xFF,
                                                     (x_end - 1) & 0xFF,
                                                 },
                              4);
    esp_lcd_panel_io_tx_param(io, LCD_CMD_RASET, (uint8_t[]){
                                                     (y_start >> 8) & 0xFF,
                                                     y_start & 0xFF,
                                                     ((y_end - 1) >> 8) & 0xFF,
                                                     (y_end - 1) & 0xFF,
                                                 },
                              4);
    // transfer frame buffer
    size_t len = (x_end - x_start) * (y_end - y_start) * r61581->fb_bits_per_pixel / 8;
    esp_lcd_panel_io_tx_color(io, LCD_CMD_RAMWR, color_data, len);

    return ESP_OK;
}

static esp_err_t panel_r61581_invert_color(esp_lcd_panel_t* panel, bool invert_color_data)
{
    r61581_panel_t*           r61581  = __containerof(panel, r61581_panel_t, base);
    esp_lcd_panel_io_handle_t io      = r61581->io;
    int                       command = 0;
    if(invert_color_data)
    {
        command = LCD_CMD_INVON;
    }
    else
    {
        command = LCD_CMD_INVOFF;
    }
    esp_lcd_panel_io_tx_param(io, command, NULL, 0);
    return ESP_OK;
}

static esp_err_t panel_r61581_mirror(esp_lcd_panel_t* panel, bool mirror_x, bool mirror_y)
{
    r61581_panel_t*           r61581 = __containerof(panel, r61581_panel_t, base);
    esp_lcd_panel_io_handle_t io     = r61581->io;
    if(mirror_x)
    {
        r61581->madctl_val |= LCD_CMD_MX_BIT;
    }
    else
    {
        r61581->madctl_val &= ~LCD_CMD_MX_BIT;
    }
    if(mirror_y)
    {
        r61581->madctl_val |= LCD_CMD_MY_BIT;
    }
    else
    {
        r61581->madctl_val &= ~LCD_CMD_MY_BIT;
    }
    esp_lcd_panel_io_tx_param(io, LCD_CMD_MADCTL, (uint8_t[]){r61581->madctl_val}, 1);
    return ESP_OK;
}

static esp_err_t panel_r61581_swap_xy(esp_lcd_panel_t* panel, bool swap_axes)
{
    r61581_panel_t*           r61581 = __containerof(panel, r61581_panel_t, base);
    esp_lcd_panel_io_handle_t io     = r61581->io;
    if(swap_axes)
    {
        r61581->madctl_val |= LCD_CMD_MV_BIT;
    }
    else
    {
        r61581->madctl_val &= ~LCD_CMD_MV_BIT;
    }
    esp_lcd_panel_io_tx_param(io, LCD_CMD_MADCTL, (uint8_t[]){r61581->madctl_val}, 1);
    return ESP_OK;
}

static esp_err_t panel_r61581_set_gap(esp_lcd_panel_t* panel, int x_gap, int y_gap)
{
    r61581_panel_t* r61581 = __containerof(panel, r61581_panel_t, base);
    r61581->x_gap          = x_gap;
    r61581->y_gap          = y_gap;
    return ESP_OK;
}

static esp_err_t panel_r61581_disp_on_off(esp_lcd_panel_t* panel, bool on_off)
{
    r61581_panel_t*           r61581  = __containerof(panel, r61581_panel_t, base);
    esp_lcd_panel_io_handle_t io      = r61581->io;
    int                       command = 0;
    if(on_off)
    {
        command = LCD_CMD_DISPON;
    }
    else
    {
        command = LCD_CMD_DISPOFF;
    }
    esp_lcd_panel_io_tx_param(io, command, NULL, 0);
    return ESP_OK;
}
